<template>
  <div class="contanier">
    <div class="contanier-title">用户管理</div>
    <search-form>
      <template v-slot:formLeft>
        <el-form :inline="true" :model="userFormLine" class="demo-form-inline">
          <el-row>
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <el-form-item label="姓名" label-width="100px">
                  <el-input
                    v-model="userFormLine.keyword"
                    placeholder="请输入姓名"
                    maxlength="16"
                    class="set-form-inline-btn"
                  ></el-input>
                </el-form-item></div
            ></el-col>
            <el-col :span="6"
              ><div class="grid-content bg-purple-light">
                <el-form-item label="性别" label-width="100px">
                  <el-select
                    v-model="userFormLine.gender"
                    placeholder="请选择性别"
                    label-width="100px"
                    class="set-form-inline-btn"
                  >
                    <el-option
                      v-for="item in genderTreeData"
                      :key="item.enCode"
                      :label="item.fullName"
                      :value="item.enCode"
                    />
                  </el-select>
                </el-form-item></div
            ></el-col>
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <el-form-item label="单位级别" label-width="100px">
                  <el-select
                    v-model="userFormLine.unitLevel"
                    placeholder="请选择单位级别"
                    class="set-form-inline-btn"
                  >
                    <el-option
                      v-for="item in dwjbData"
                      :key="item.enCode"
                      :label="item.fullName"
                      :value="item.enCode"
                    />
                  </el-select>
                </el-form-item></div
            ></el-col>
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <el-form-item label="省市县" label-width="100px">
                  <Address
                    v-model="userFormLine.areaIdArr"
                    placeholder="请选择"
                    clearable
                    :level="1"
                    :multiple="false"
                    style="width: 140px;"
                  />
                </el-form-item></div
            ></el-col>
          </el-row>
          <el-row>
            <el-col :span="6"
              ><div class="grid-content bg-purple-light">
                <el-form-item label="单位性质" label-width="100px">
                  <el-select
                    v-model="userFormLine.unitNature"
                    placeholder="请选择单位性质"
                    class="set-form-inline-btn"
                  >
                    <el-option
                      v-for="item in dwxzData"
                      :key="item.enCode"
                      :label="item.fullName"
                      :value="item.enCode"
                    />
                  </el-select>
                </el-form-item></div
            ></el-col>
            <el-col :span="6"
              ><div class="grid-content bg-purple-light">
                <el-form-item label="角色" label-width="100px">
                  <el-select
                    v-model="userFormLine.roleId"
                    placeholder="选择角色"
                    @change="onChange('js')"
                    multiple
                    filterable
                    clearable
                    class="set-form-inline-btn"
                  >
                    <el-option-group
                      v-for="group in roleTreeData"
                      :key="group.id"
                      :label="
                        group.fullName +
                        (group.num ? '【' + group.num + '】' : '')
                      "
                    >
                      <el-option
                        v-for="item in group.children"
                        :key="group.id + item.id"
                        :label="item.fullName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item></div
            ></el-col>
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <el-form-item label="状态" label-width="100px">
                  <el-select
                    class="set-form-inline-btn"
                    v-model="userFormLine.enabledMark"
                    placeholder="选择状态"
                  >
                    <el-option label="正常" :value="1" />
                    <el-option label="锁定" :value="2" />
                    <el-option label="禁用" :value="0" />
                  </el-select>
                </el-form-item></div
            ></el-col>
          </el-row>
        </el-form>
      </template>
      <template v-slot:formRight>
        <div class="formRight-btn">
          <el-button
            icon="el-icon-refresh"
            class="overPosBtn"
            @click="clearFrom"
            style="width: 104px;"
            >重 置</el-button
          >
          <el-button
            type="primary"
            @click="onSearch"
            icon="el-icon-search"
            class="set-col-btn"
            style="width: 104px;"
            >查 询</el-button
          >
        </div>
      </template>
    </search-form>
    <div>
      <search-table>
        <template v-slot:daochu>
          <div class="set-table-right">
            <el-button icon="el-icon-my-message" @click="exportUser">导 出</el-button>
          </div>
        </template>
        <template v-slot:biaoge>
          <template>
            <el-table
              :key="tableKey"
              ref="multipleTable"
              :data="tableData"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange"
              class="table-top"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="姓名" width="120">
                <template slot-scope="scope">{{ scope.row.realName }}</template>
              </el-table-column>
              <el-table-column prop="mobilePhone" label="联系电话" width="130">
              </el-table-column>
              <el-table-column prop="roleName" label="角色"> </el-table-column>
              <el-table-column prop="gender" label="性别">
                <template slot-scope="scope">{{
                  scope.row.gender == 1 ? "男" : "女"
                }}</template>
              </el-table-column>
              <el-table-column prop="age" label="年龄"> </el-table-column>
              <el-table-column prop="ssx" label="省市县名称">
                <template slot-scope="scope">
                  {{ scope.row.areaId ? areaNameMap[scope.row.areaId] : '' }}
                </template>
              </el-table-column>
              <el-table-column prop="organize" label="单位性质">
                <template slot-scope="scope">
                  {{ unitNatureMap[scope.row.unitNature] }}
                </template>
              </el-table-column>
              <el-table-column prop="organize" label="单位级别">
                <template slot-scope="scope">
                  {{ unitLevelMap[scope.row.unitLevel] }}
                </template>
              </el-table-column>
              <el-table-column prop="enabledMark" label="状态">
                <template slot-scope="scope">
                  <!-- enabledmark 1: 正常，0：禁用 -->
                  <el-switch
                    v-model="scope.row.enabledMark"
                    active-color="#2265EE"
                    inactive-color="#DBDFEA"
                    :active-value="1" 
                    :inactive-value="0"
                    @change="(val) => switchChange(val, scope.row)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="180">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="editRow(scope.row, false)"
                    type="text"
                    size="small"
                    class="set-table-btn set-table-btn-col"
                    icon="el-icon-edit"
                  >
                    编辑
                  </el-button>
                  <el-button
                    @click.native.prevent="editRow(scope.row, true)"
                    type="text"
                    size="small"
                    class="set-table-btn set-table-btn-col"
                    icon="el-icon-edit"
                  >
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </template>
        <template v-slot:fenye>
          <div class="set-table-pg-right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </template>
      </search-table>
    </div>
  </div>
</template>
<script>
import define from "@/utils/define";
import SearchForm from "@/components/search-form";
import SearchTable from "@/components/search-table";
import { getRoleByOrganize } from "@/api/permission/role";
import {
  GetAreaByIds,
} from "@/api/system/province";
import { getuserList, exportUserList, updateEnableMark } from "@/api/userManagerment";
export default {
  name: "UserManagement",
  components: {
    SearchForm,
    SearchTable,
  },
  data() {
    return {
      genderTreeData: [],
      dwjbData: [],
      dwxzData: [],
      userFormLine: {
        keyword: "",
        gender: "",
        unitLevel: "",
        unitNature: "",
        roleId: [],
        enabledMark: "",

        sex: "",
        unit: "",
        xz: "",
        ssxmc: "",
        js: "",
        zt: "",
      },
      tableData: [],
      tableColumns: [
        {
          label: "姓名",
          prop: "xm",
        },
        {
          label: "性别",
        },
      ],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      roleTreeData: [],
      tableKey: 0,
      areaNameMap: {},
      unitNatureMap: {},
      unitLevelMap: {}
    };
  },
  created() {
    this.getZD();
  },
  mounted() {
    this.loadData();
  },
  methods: {
    switchChange(e, row) {
      // row.enabledmark = e;
      updateEnableMark(row.id, e)
        .then((res) => {
          this.$message({
            message: "操作成功",
            type: "success",
          });
        })
        .catch((e) => {
          this.$message.error("操作失败");
        });
    },
    loadData() {
      const params = {
        ...this.userFormLine,
        roleId: this.userFormLine.roleId.join(","),
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      };
      getuserList(params)
        .then((res) => {
          this.loadAreaName(res.data.list);
          this.tableData = res.data.list;
          this.total = res.data.pagination.total;
          this.tableKey++;
        })
        .catch((e) => {
          console.log(e);
        });
    },
    loadAreaName(list) {
      for(let i = 0; i < list.length; i++) {
        const data = list[i];
        if (!data.areaId) {
          return;
        }
        const selectedIds = [data.areaId.split(',')];
        GetAreaByIds(selectedIds).then(res => {
          const selectedData = res.data.map((o) => o.join("/"));
          this.areaNameMap[data.areaId] = selectedData.join(",");
          console.log(this.areaNameMap, '====areaNameMap==');
          this.tableKey++;
        })
      }
    },
    clearFrom() {
      this.userFormLine = {
        keyword: "",
        gender: "",
        unitLevel: "",
        unitNature: "",
        roleId: [],
        enabledMark: "",

        sex: "",
        unit: "",
        xz: "",
        ssxmc: "",
        js: "",
        zt: "",
      };
      this.currentPage = 1;
      this.tableData = [];
      this.loadData();
    },
    onSearch() {
      this.currentPage = 1;
      this.tableData = [];
      let data = this.userFormLine.areaIdArr;
      if (data) {
        this.userFormLine.areaId = data[data.length - 1];
        delete this.userFormLine.areaIdArr;
      }
      // console.log(data,this.userFormLine.areaId,'====data====1');

      // const result = data
      //   .map(subArray => {
      //     const lastItem = subArray[subArray.length - 1];
      //     const parts = lastItem.split(',');
      //     return parts[parts.length - 1];
      //   })
      //   .join(',');
      // this.userFormLine.areaId = result;
      // delete this.userFormLine.areaIdArr;

      this.loadData();
    },
    handleSelectionChange(val) { 
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.tableData = [];
      this.loadData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadData();
    },
    editRow(row, type) {
      this.$router.push({
        name: "userManagemntEdit",
        query: { id: row.id, detailStatus: type }
      });
    },
    getZD() {
      // 获取性别
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "sex",
        })
        .then((res) => {
          this.genderTreeData = res;
        });
      // 获取单位级别
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "EnterpriseGrade",
        })
        .then((res) => {
          res.forEach(item => {
            this.unitLevelMap[item.enCode] = item.fullName
          });
          this.dwjbData = res;
          this.tableKey++;
        });
      // 获取单位性质
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "EnterpriseNature",
        })
        .then((res) => {
          res.forEach(item => {
            this.unitNatureMap[item.enCode] = item.fullName
          });
          this.dwxzData = res;
          this.tableKey++;
        });
      getRoleByOrganize().then((res) => {
        res.data.list.forEach(item => {
          item.children = item.children.filter(v => v.fullName != '管理员' && v.fullName != '游客')
        });
        this.roleTreeData = res.data.list.filter(
          (o) => o.children && Array.isArray(o.children) && o.children.length
        );
      });
    },
    onChange(key) {
      this.userFormLine[key] = this[key].join();
    },
    // 导出用户
    exportUser() {
      let data = {
        ...this.userFormLine,
        currentPage: this.currentPage,
        pageSize: 10000,
      };
      let paras = "selectKey=roleId,mobilePhone,roleName,gender,age,areaName,unitNature,unitLevel&dataType=0"
      exportUserList(paras,data).then(res => {
        if (res.code === 200) {
          this.jsbos.downloadFile(res.data.url);
        }
      })
    }
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-icon-my-message {
  background: url("../../assets/images/dc.png") no-repeat;
  width: 20px !important;
  height: 20px !important;
}

::v-deep .el-icon-my-message:before {
  content: "替";
  font-size: 20px;
  visibility: hidden;
}

::v-deep .el-icon-my-message {
  font-size: 18px;
}

::v-deep .el-icon-my-message:before {
  content: "\e611";
}
</style>
